
import json
import random
from flask_restful import reqparse
from db import dp
from application.models.users.user import *


from flask import Blueprint,request,jsonify

from tools.myredis import r

good_blue = Blueprint("goodblue",__name__)

# 提交订单
# 调用支付宝  进行购买
import datetime
from tools.comm.comm import get_ali_object
@good_blue.route('/settlement',methods=["POST"])
def settlement():
    data=json.loads(request.data)
    userid=int(data["userid"])
    tmoney=int(data["tmoney"])
    cid=int(data["cid"])
    #幂等性token
    key = "mdtoken" + str(userid)
    sum=0
    sql = "select * from cart where userid=%d" % userid
    res=dp.find_all(sql)
    if not res:
        return jsonify({"code":500,"msg":"没有该商品"})
    sum+=float(tmoney)
    print(sum)
    # 订单号
    number = int(str(userid) + str(random.randint(1000, 9999)))
    create_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
    update_time = datetime.datetime.strftime(datetime.datetime.now(), "%Y-%m-%d %H:%M:%S")
    status = 2
    # usql = Vipuser_course(courseid=cid,userid=userid)
    # db.session.add(usql)
    # print(usql,'////////////////////////////')
    isql = Orders(create_time=create_time,update_time=update_time,userid=userid,courseid=cid,number=number,tmoney=sum,status=status,price=sum)
    db.session.add(isql)
    db.session.commit()
    print(isql,'111111111111111111111111')
    sqlcart = Cart.query.filter(Cart.userid==userid).first()
    db.session.delete(sqlcart)
    print(sqlcart,'22222222222222222222222')
    db.session.commit()
    #删除幂等性token
    r.del_key(key)
    # 支付
    oreder_no = str(number) + "," + str(2)
    alipay = get_ali_object()
    query_params = alipay.direct_pay(
        subject=str(userid) + "购买课程",  # 商品简单描述
        out_trade_no=oreder_no,  # 用户购买的商品订单号（每次不一样） 20180301073422891
        total_amount=sum,  # 交易金额(单位: 元 保留俩位小数)
    )
    pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）
    return jsonify({
        'code': 200,
        'url': pay_url
    })

# 加入购物车
@good_blue.route('/addgood',methods=["POST"])
def addshop():
    req = reqparse.RequestParser()
    req.add_argument('userid')
    req.add_argument('id')
    args = req.parse_args()

    if not all({args['userid'],args['id']}):
        return jsonify({'code':400,'msg':'数据不存在'})

    cart = Cart.query.filter(Cart.cid == args['id']).first()
    print(cart)
    if cart:
        sql = "update Cart set count=count+1 where cart.cid=%d"%int(args['id'])
        dp.add(sql)
        dp.commit()
        return jsonify({'code':200,'msg':'ok'})
    else:
        count = 1
        sql = "insert into cart(userid,cid,count) values('%d','%d','%d')"%(int(args['userid']),int(args['id']),int(count))
        dp.add(sql)
        dp.commit()
        return jsonify({'code':200,'msg':'加入购物车成功'})

# 购物车数量加
@good_blue.route('/addcount',methods=["POST"])
def Add_count():
    req = reqparse.RequestParser()
    req.add_argument('userid')
    req.add_argument('id')
    args = req.parse_args()

    if not all({args['id'], args['userid']}):
        return jsonify({'code': 400, 'msg': '数据不存在'})

    sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int(args['userid']), int(args['id']))
    res = dp.find_all(sql)
    for i in res:
        sql1 = "update Cart set count=count+1 where cart.userid=%d and cart.cid=%d" % (int(i['userid']), int(args['id']))
        dp.add(sql1)
        dp.commit()
    return jsonify({'code':200,'msg':'ok'})

# 购物车数量减
@good_blue.route('/mincount',methods=["POST"])
def Min_count():
    req = reqparse.RequestParser()
    req.add_argument('userid')
    req.add_argument('id')
    args = req.parse_args()

    if not all({args['id'], args['userid']}):
        return jsonify({'code': 400, 'msg': '数据不存在'})

    sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int(args['userid']), int(args['id']))
    res = dp.find_all(sql)
    for i in res:
        sql1 = "update Cart set count=count-1 where cart.userid=%d and cart.cid=%d" % (int(i['userid']), int(args['id']))
        dp.add(sql1)
        dp.commit()
    return jsonify({'code':200,'msg':'ok'})

# 删除购物车数据
@good_blue.route('/delcount',methods=["POST"])
def Del_count():
    req = reqparse.RequestParser()
    req.add_argument('userid')
    req.add_argument('id')
    args = req.parse_args()

    if not all({args['id'], args['userid']}):
        return jsonify({'code': 400, 'msg': '数据不存在'})

    sql = "select * from cart where cart.userid = %d and cart.cid = %d" % (int(args['userid']), int(args['id']))
    res = dp.find_all(sql)
    for i in res:
        sql1 = "delete from cart where cart.userid=%d and cart.cid=%d" % (int(i['userid']), int(args['id']))
        dp.add(sql1)
        dp.commit()
    return jsonify({'code':200,'msg':'ok'})


# from db import db
# 获取训练营里面得所有数据
@good_blue.route('/getxly')
def getxly():
    sql = 'select * from tcourse'
    res = dp.find_all(sql)
    return jsonify({'code':200,'msg':'ok','data':res})

@good_blue.route('/getcourse')
def getcourse():
    req = reqparse.RequestParser()
    req.add_argument('userid')
    args = req.parse_args()
    list = []
    sql = "select * from cart where cart.userid=%d"%int(args['userid'])
    res = dp.find_all(sql)
    for i in res:
        sql1 = "select * from tcourse where tcourse.id=%d"%int(i['cid'])
        res1 = dp.find_all(sql1)
        for j in res1:
            list.append({
                'id':j['id'],
                'title':j['title'],
                'price':j['price'],
                'count':i['count'],
                'url':j['url'],
                'amount':(j['price'] * i['count'])
            })
            tmoney = j['price'] * i['count']
            cid = i['cid']
            money = j['price']
            count = i['count']
            return jsonify({'code':200,'msg':'ok','data':list,"tmoney": tmoney, "cid": cid,'money':money,'count':count})


from application.models.users.user import db
@good_blue.route("/crecom",methods=['POST'])
def createes():
    data = json.loads(request.data)
    title = data['title']
    userid = data['userid']
    pid = data['pid']
    print(userid,pid,title)
    if not pid:
        #首个评论
        comm = Comment(title=title,userid=userid,typepid=1,pid=0)
        db.session.add(comm)
        print(">>>>....")
        db.session.commit()
    else:
        com = Comment.query.filter(Comment.id==pid).first()
        print("com",com.id)
        if com:
            coms = Comment(title=title,userid=userid,typepid=2,pid=com.id)
            db.session.add(coms)
            print(coms,">?")
            coms_info = Comment.query.filter(Comment.pid==pid).first()
            print(coms_info,"///")
            if not coms_info:
                coms.is_last = 1
                print("11")
            else:
                coms.is_last = 0
                print("00")
            db.session.commit()
        else:
            return jsonify({"code":404,"msg":"评论已删除"})
    return jsonify({"code":200,"msg":"ok"})

#获取评论
def showuser(data):   #封装方法 也可以写进类视图中
    list2=[]
    dict2={}
    for i in data:
        k = i['id']
        dict2[k]=i

    for j in data:
        pid=j['pid']
        if pid == 0:   #如果为空说明是第一级
            list2.append(j)
        else:
            if 'son' not in dict2[pid]:   #判断是否有下级分类
                dict2[pid]['son'] = []
            dict2[pid]['son'].append(j)   #添加进去
    return list2

@good_blue.route("/comment")
def get():
    user_info = Comment.query.all()
    user_data = []
    for i in user_info:
        a = {
            'id':i.id,
            'title': i.title,
            'tcount': i.tcount,
            'tviews': i.tviews,
            'is_last': i.is_last,
            'is_top': i.is_top,
            'userid': i.userid,
            'typepid': i.typepid,
            'pid': i.pid,
        }
        user_data.append(a)
    ss=showuser(user_data)    #调用方法 并传参
    return jsonify({'code':200,'data':ss})

